package common.web.action;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import common.hibernate.service.BaseService;
import common.log.service.LogService;
import common.log.util.LogModule;
import common.log.util.LogType;
import common.log.vo.WebLog;
import common.rbac.po.Group;
import common.rbac.po.GroupRole;
import common.util.JSONUtils;
import common.web.vo.Result;

@Controller
@RequestMapping("/system/group")
public class GroupAction extends CommonAction {

	private static final Logger logger = Logger.getLogger(GroupAction.class);

	@Autowired
	@Qualifier("baseServiceImpl")
	protected BaseService baseService;
	
	@Autowired
	private LogService logService;
	
	

	@RequestMapping("/view/{id}")
	@ResponseBody
	public Result view(@PathVariable String id) {
		Group group = this.baseService.get(Group.class, id);
		if (null == group) {
			return Result.fail("组织机构不存在");
		}
		Result result = Result.createResult(group);
		// 查询关联的权限
		result.addMap("roles", this.baseService.find("select r from GroupRole gr,Role r where gr.roleId = r.id and gr.groupId = ?", group.getId()));
		return result;
	}

	@RequestMapping("/list")
	@ResponseBody
	public Result list(@RequestBody(required = false) JSONObject json) {
		String parentId = json.getString("parentId");
		String sql = null;
		ArrayList<Object> params = new ArrayList<>();
		if (StringUtils.isNotBlank(parentId)) {
			sql = "from Group where parentId = ? order by sort";
			params.add(parentId);
		} else {
			sql = "from Group where parentId is null order by sort";
		}
		return Result.createResult(baseService.find(sql, params.toArray()));
	}
	
	@RequestMapping("/listAll")
	@ResponseBody
	public Result listAll() {
		String sql = "from Group order by sort";
		return Result.createResult(baseService.find(sql));
	}

	@RequestMapping("/{editType}")
	@ResponseBody
	public Result save(@PathVariable String editType, @RequestBody JSONObject json) {
		Group group = JSONUtils.toJavaObject(json.getJSONObject("entity"), Group.class);
		List<GroupRole> grs = JSONUtils.toJavaObject(json.getJSONArray("roles"), GroupRole.class);
		if (null != group) {
			WebLog log = new WebLog(LogModule.GROUP, LogType.ADD, "操作失败");
			if("update".equals(editType)) {
				log.setType(LogType.UPDATE);
			}
			try {
				// 删除关联部分
				if ("update".equals(editType)) {
					// 关联的查询出来一起删除
					GroupRole grl = new GroupRole();
					grl.setGroupId(group.getId());
					List<GroupRole> deletes = baseService.findByExample(grl);
					super.setCommonUpdateInfo(group);
					baseService.dbOperation(grs.toArray(), new Object[] { group }, deletes.toArray());
					log.setSuccess(MessageFormat.format("修改组织机构[{0}]成功!", group.getName()));
				} else if ("add".equals(editType)) {
					List<Object> saves = new ArrayList<Object>();
					super.setCommonSaveInfo(group);
					saves.add(group);
					for (GroupRole gr : grs) {
						gr.setGroupId(group.getId());
					}
					saves.addAll(grs);
					baseService.save(saves.toArray());
					
					log.setSuccess(MessageFormat.format("新增组织机构[{0}]成功!", group.getName()));
				}
			} catch (Exception e) {
				log.setFail(MessageFormat.format("操作组织机构[{0}]失败!", group.getName()));
				logger.error("", e);
				
				return Result.fail("数据错误，请刷新后重试");
			} finally {
				logService.saveLog(log);
			}
		} else {
			return Result.fail("数据错误，请刷新后重试");
		}
		return Result.SUCCESS;
	}

	@RequestMapping("/delete/{id}")
	@ResponseBody
	public Result delete(@PathVariable String id) {
		Group load = baseService.load(Group.class, id);
		if (null != load) {
			WebLog log = new WebLog(LogModule.GROUP, LogType.DELETE, "操作失败");
			try {
				String hql = "from Group where parentId = ?";
				List<Object> find = baseService.find(hql, load.getId());
				if(null != find && find.size() > 0){
					String msg = MessageFormat.format("[{0}]存在关联的子机构,不能删除该机构!", load.getName());
					log.setFail(msg);
					return Result.fail(msg);
				}
				
				String deleteHql = "delete from GroupRole where groupId = ?";
				baseService.dbOperation(deleteHql, new Object[] { load.getId() }, null, null, new Object[] { load });
				
				// 日志
				log.setSuccess(MessageFormat.format("删除组织机构[{0}]成功!", load.getName()));
			} catch (Exception e) {
				log.setFail(MessageFormat.format("删除组织机构[{0}]失败!", load.getName()));
				logger.error("", e);
				
				return Result.fail("删除失败");
			} finally {
				logService.saveLog(log);
			}
		} else {
			return Result.fail("组织机构不存在");
		}
		return Result.SUCCESS;
	}
}
